﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using MiniExcelLibs;
using SheepStorage.API.Application.Command.ProviderManageCommand;
using SheepStorage.API.Baseclass;
using SheepStorage.Domain.Dto.InputDto;
using SheepStorage.Domain.Entity;
using SheepStorage.Service.Interface;

namespace SheepStorage.API.Application.CommandHandlers.ProviderManageHandler
{
    public class ProviderManageExportHandler: IRequestHandler<ProviderManageExportCommand, IActionResult>
    {
        private readonly IProviderManageService _providerService;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="providerService"></param>
        /// <param name="mapper"></param>
        public ProviderManageExportHandler(IProviderManageService providerService, IMapper mapper)
        {
            _providerService = providerService;
            _mapper = mapper;
        }
        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<IActionResult> Handle(ProviderManageExportCommand request, CancellationToken cancellationToken)
        {
            //获取数据列表
            var list =await _providerService.GetProviderManage(request.Input);

            //获取数据
            var data = list.Data;

            //转换为导出类型
            var exportCustomerDto = _mapper.Map<List<ProviderManage>, List<ProviderManageInput>>(data);

            // 创建一个内存流对象
            MemoryStream ms = new MemoryStream();

            // 异步将导出的客户数据保存到内存流中
            await ms.SaveAsAsync(exportCustomerDto);

            // 将内存流的读取位置重置到开始位置
            ms.Seek(0, SeekOrigin.Begin);

            // 返回一个文件流结果，指定内容类型和文件下载名
            return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "客户信息.xlsx"
            };
        }
    }
}
